package cn.edu.pku.sei.ra.selfadapt.actions;

import java.util.Collections;

import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.MenuItem;

import cn.edu.pku.sei.ra.framework.CausalConnector;
import cn.edu.pku.sei.ra.selfadapt.OCLAnnoExec;

public class ManagementAgentListener implements SelectionListener {
	
	public static Thread THREAD=null;
	
	private int interval=0;
	private CausalConnector cc=null;
	private OCLAnnoExec exec=null;
	private MenuItem mi=null;
	
	public ManagementAgentListener(OCLAnnoExec exec,CausalConnector cc, int interval, MenuItem mi){
		this.interval=interval*1000;
		if(this.interval<1000)
			this.interval=1000;
		this.cc=cc;
		this.exec=exec;
		this.mi=mi;
	}

	@Override
	public void widgetDefaultSelected(SelectionEvent e) {
		//if(e.)

	}

	@Override
	public void widgetSelected(SelectionEvent e) {
		if(mi.getSelection()){
			THREAD=new Thread(new DiamondRunning());
			THREAD.start();
		}
		else{
			THREAD.stop();
			THREAD.destroy();
			THREAD=null;
		}
	}
	
	private class DiamondRunning implements Runnable{
		public void run(){	
			while(true){
				try{
					if(cc!=null){
						cc.silentMaintain();
					}
					Resource res=exec.execute();
					res.save(Collections.EMPTY_MAP);
					if(cc!=null){
						cc.silentMaintain();
					}
					Thread.sleep(interval);
				}
				catch(Exception e){
					e.printStackTrace();
					break;
				}
				
			}
		}
	}

}
